package com.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 216. 组合总和 III
 *
 * @author fy
 * @date 2022/4/28 22:17
 */
public class Solution216 {

    private List<List<Integer>> res;
    private final static int[] NUMS = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};

    public List<List<Integer>> combinationSum3(int k, int n) {
        res = new ArrayList<>();
        dfs(n, k, 0, new ArrayList<>());
        return res;
    }

    private void dfs(int n, int k, int index, List<Integer> preList) {
        if (preList.size() == k && n == 0) {
            res.add(new ArrayList<>(preList));
            return;
        }
        if (preList.size() == k) {
            return;
        }
        for (int i = index; i < NUMS.length; i++) {
            int num = NUMS[i];
            if (n - num < 0) {
                break;
            }
            preList.add(num);
            n -= num;
            dfs(n, k, i + 1, preList);
            n += num;
            preList.remove(preList.size() - 1);
        }
    }

}
